<script setup lang="ts">
import { request } from '@/api'
import { showLoadingToast, showToast, type ActionSheetAction } from 'vant'
import { onMounted, ref } from 'vue'
import b64toBlob from 'b64-to-blob'
//-----修改头像系列--------
const showAvatarSheet = ref(false)
const actions = [{ name: '拍照' }, { name: '从相册选择' }, { name: '取消' }]
const onCancel = () => {
  console.log('取消')
}
const onSelect = async (action: ActionSheetAction, index: number) => {
  //捕获取消相册的提示语
  try {
    if (index == 0) {
      const res = await mk.Camera()
      console.log('拍照', res)

      //调用修改头像方法
      updateAvatar(res)
    }
    if (index == 1) {
      console.log('从相册选择')
      const res = await mk.getPhoto()
      console.log('相册路径:' + res)

      //调用修改头像方法
      updateAvatar(res)
    }
  } catch (err) {
    console.log('错误' + JSON.stringify(err));
    showToast('上传失败')
  }
}
//修改头像方法
const updateAvatar = async (data: string) => {
  try {
    //通过b64toBlob方法将base64转为二进制
    const img = b64toBlob(data, 'image/jpeg')
    console.log('拍照成功', img);
    //创建一个FormData对象
    const formData = new FormData()
    //追加数据 file:接口需要的键
    formData.append('file', img, Date.now() + '.jpeg')
    //开启加载弹窗
    const showLoad = showLoadingToast({
      message: '加载中...',
      forbidClick: true,
      loadingType: 'spinner',
    });
    //发送请求
    const uploadRes = await request({
      method: 'post',
      url: 'member/profile/avatar',
      data: formData
    })
    console.log('请求接口后的地址:' + JSON.stringify(uploadRes));

    //更新头像
    user.value.avatar = uploadRes.data.result.avatar

    //关闭加载弹窗
    showLoad.close()
    //更新鸿蒙端头像
    // 1.获取鸿蒙端用户信息
    const userInfo = mk.getUser();
    userInfo.avatar = uploadRes.data.result.avatar
    // 2.更新用户信息
    mk.saveUser(userInfo)



  } catch (err) {
    console.log('错误' + JSON.stringify(err));
    showToast('上传失败')
  }

}

//----------日期弹窗系列--------
const showBottom = ref(false) //弹出日期弹窗
const currentDate = ref<string[]>([]) //当前日期
const minDate = new Date(1997, 0, 1) //最小日期
const maxDate = new Date(2035, 12, 31) //最大日期
//确认按钮
const onConfirm = () => {
  console.log(currentDate.value)
  user.value.birthday = currentDate.value.join('-')
  showBottom.value = false
}

//-----省市区系列-------
const areaList = ref<AreaColumns>({
  province_list: {
    110000: '北京市',
    120000: '天津市',
  },
  city_list: {
    110100: '北京市',
    120100: '天津市',
  },
  county_list: {
    110101: '东城区',
    110102: '西城区',
    // ....
  },
})
const showArea = ref(false)
// 省市区弹窗点击确定
const onConfirmArea = ({ selectedValues, selectedOptions, selectedIndexes }: { selectedValues: number[]; selectedOptions: { text: string }[]; selectedIndexes: number[] }) => {
  console.log(selectedValues, selectedOptions, selectedIndexes)
  const arr = selectedOptions.map((item: { text: string }) => item.text)
  console.log(arr);
  //获取省市区名称
  user.value.fullLocation = arr.join(' ')
  //获取省市区code
  user.value.provinceCode = selectedValues[0].toString()
  user.value.cityCode = selectedValues[1].toString()
  user.value.countyCode = selectedValues[2].toString()


  showArea.value = false
}
//职业弹窗
const columns = [
  { text: '前端开发', value: '前端开发' },
  { text: '后端开发', value: '后端开发' },
  { text: '鸿蒙开发', value: '鸿蒙开发' },
  { text: '安卓开发', value: '安卓开发' },
  { text: '机械工程师', value: '机械工程师' },
  { text: '市场营销专员', value: '市场营销专员' },
]
const showJob = ref(false)
const jobValue = ref<string[]>([])
//职业选择
const onConfirmJob = ({ selectedValues }: { selectedValues: string[] }) => {
  showToast(`当前值: ${selectedValues.join(',')}`)
  //修改弹窗的值保存
  user.value.profession = jobValue.value.join(',')
  showJob.value = false
}

//----请求接口获取用户信息回显表单----
const user = ref<ProfileInfo>({} as ProfileInfo)
onMounted(async () => {
  // 获取省列表
  const data = await mk.getAreaColumns()
  areaList.value = data

  //获取用户信息
  const res = await request<MkResponse<ProfileInfo>>({
    url: 'member/profile',
  })
  user.value = res.data.result
  //职业
  jobValue.value = [user.value.profession]
  //生日列表和弹窗中数据保存一致
  currentDate.value = user.value.birthday.split('-')



  console.log(user.value)
})

//修改用户信息并提交
const onSubmit = async () => {
  //开启加载弹窗
  const updateShowLoad = showLoadingToast({
    message: '加载中...',
    forbidClick: true,
    loadingType: 'spinner',
  });
  const res = await request<MkResponse<ProfileInfo>>({
    url: 'member/profile',
    method: 'put',
    data: user.value
  })
  console.log('打印提交信息', res);
  updateShowLoad.close()
  showToast('修改成功')

  //更新数据到鸿蒙端
  mk.saveUser(res.data.result)

}

</script>

<template>
  <div class="profile-edit-page">
    <!-- 头像部分 -->
    <div class="avatar">
      <van-image round width="100" height="100" class="avatar-img" :src="user.avatar" @click="showAvatarSheet = true">
      </van-image>
      <div class="avatar-btn">
        <span @click="showAvatarSheet = true">修改头像</span>
      </div>
    </div>
    <!-- 点击展示底部弹窗组件 -->
    <van-action-sheet v-model:show="showAvatarSheet" :actions="actions" cancel-text="取消" close-on-click-action
      @cancel="onCancel" @select="onSelect" />

    <!-- 中间表单部分 -->
    <van-cell-group>
      <van-field label="账号" v-model="user.account" readonly></van-field>
      <van-field label="昵称" v-model="user.nickname" placeholder="请输入昵称"></van-field>
      <van-cell title="性别" class="gender">
        <van-radio-group v-model="user.gender" :icon-size="16">
          <van-radio name="男">男</van-radio>
          <van-radio name="女">女</van-radio>
          <van-radio name="未知">未知</van-radio>
        </van-radio-group>
      </van-cell>
      <van-field label="生日" @click="showBottom = true" readonly placeholder="请选择日期" v-model="user.birthday"></van-field>
      <van-field label="所在地" @click="showArea = true" readonly placeholder="请选择所在地"
        v-model="user.fullLocation"></van-field>
      <van-field label="职业" v-model="user.profession" @click="showJob = true" readonly placeholder="请选择职业"></van-field>
    </van-cell-group>

    <!-- 获取生日->日历弹窗 -->
    <van-popup v-model:show="showBottom" position="bottom" :style="{ height: '45%' }">
      <van-date-picker v-model="currentDate" title="选择日期" :min-date="minDate" :max-date="maxDate" @confirm="onConfirm"
        @cancel="showBottom = false" />
    </van-popup>
    <!-- 省市区弹窗 -->
    <van-popup v-model:show="showArea" position="bottom" :style="{ height: '45%' }">
      <van-area title="选择地区" :area-list="areaList" @cancel="showArea = false" @confirm="onConfirmArea" />
    </van-popup>

    <!-- 职业弹窗 -->
    <van-popup v-model:show="showJob" position="bottom" :style="{ height: '45%' }">
      <van-picker title="选择职业" :columns="columns" @cancel="showJob = false" @confirm="onConfirmJob"
        v-model="jobValue" />
    </van-popup>
    <div class="submit">
      <van-button round block type="primary" @click="onSubmit"> 保存资料 </van-button>
    </div>
  </div>
</template>

<style lang="css" scoped>
.avatar {
  padding: 30px;
  text-align: center;
  background-color: var(--mk-white);
}

.avatar-img {
  box-shadow: 0 0 5px var(--mk-gray);
}

.avatar-btn {
  color: var(--mk-linear_end);
  margin-top: 10px;
}

.gender ::v-deep(.van-cell__title) {
  width: 100px;
  flex: none;
}

.van-radio-group {
  display: flex;
  justify-content: space-between;
  height: 36px;
  width: 180px;
}

.submit {
  padding: 16px;
}
</style>
